package com.mar.meclient.util;
/**
 * TODO:  Unit tests are required.
 * @author mar
 *
 */
public class SyncBlockingQueue extends Queue {
	private final Object lock;
	
	public SyncBlockingQueue(int maxSize) {
		super(maxSize);
		this.lock = new Object();
	}
	
	public Object pop() {
		synchronized(lock){
			try {
				if ( size() == 0 ){
					lock.wait();
				}
				return super.pop();
			} catch (InterruptedException e) {
				return null;
			}
		}
	}
	
	public void push(Object element) {
		synchronized(lock){
			super.push(element);
			lock.notifyAll();
		}
	}
	
	public int size() {
		synchronized(lock){
			return super.size();
		}
	}
	
	protected void checkPushPreconditions() {
		if ( size() == maxSize() ){
			super.pop();
		}
	}

	public static void main(String[] args) {
		Queue queue = new SyncBlockingQueue(3);
		queue.push("1");
		queue.push("2");
		queue.push("3");
		queue.push("4");

		System.out.println(queue.pop());
		System.out.println(queue.pop());

		
//		System.out.println(queue.pop());
//		System.out.println(queue.pop());

//		Thread pushTread = new Thread( new Runnable(){
//			public void run() {
//				
//			}
//		} );
	}
}
